package com.leenleda.ips.receiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.activity.ImageActivity;
import com.leenleda.ips.activity.InsertActivity;
import com.leenleda.ips.activity.LiveActivity;
import com.leenleda.ips.activity.WebActivity;
import com.leenleda.ips.entity.DataEntity;
import com.leenleda.ips.entity.MarqueeEntity;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.net.NetInterface;
import com.leenleda.ips.util.FileData;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.NetUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;

import java.util.List;

public class ReceiverMsg extends BroadcastReceiver {
    public static final String PUSH_NOTICE = "111";//推送滚动消息
    public static final String PUSH_INSERT = "112";//推送插播
    public static final int SET_PWD = 9999;     //密码设置

    private String tag = "ReceiverMsg";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
//        ILog.e(tag, "=====action======" + action);
        sendBroad(context);
//        Utils.checkService(context);
        switch (action){
            case "android.intent.action.BOOT_COMPLETED":
                startSelf(context, getInfo());
                break;
            case Constant.RECEIVE_FORM_SERVICE:
                boolean isForeground = Utils.isOnForeground(context);
//                ILog.e(tag, "==bundle===isOnForeground==1====" + isForeground);
                if (BaseActivity.getForegroundActivity() == null)
                    return;
                BaseActivity.getForegroundActivity().missRollMsg(false);
                if (BaseActivity.getForegroundActivity() instanceof InsertActivity)
                    BaseActivity.getForegroundActivity().conTrollShow(Constant.MISS_INSERT_MSG);
                if (BaseActivity.getForegroundActivity() instanceof LiveActivity)
                    BaseActivity.getForegroundActivity().conTrollShow(Constant.MISS_INSERT_MSG);
                if (!isForeground || BaseActivity.getForegroundActivity() == null) {//如果有新任务发布 或则 app没有启动
                    DataEntity info = getInfo();
                    if (info == null )//没认证的话不自启
                        return;
                    startSelf(context, info);
                    return;
                }

                Bundle bundle = intent.getExtras();
                if (bundle == null)
                    return;
                DataEntity info = getInfo();
                int state = bundle.getInt("state");
                LogUtils.e(tag, "==bundle===state======" + state);
                switch (state){
                    case SET_PWD:
                        int pwd = bundle.getInt("pwd");
                        if (pwd == 0){
                            UShared.putString("set_pwd", "");
                        } else {
                            UShared.putString("set_pwd", pwd + "");
                        }
                        LogUtils.e(tag, "==bundle===pwd======" + pwd);
                        break;
                    case Constant.KILL_SELF:
                        LogUtils.e("SDFKSDF", "=======killProcess=======2=");
                        System.exit(0);
                        break;
                    case Constant.PUSH_MSG:
                        String msgData = bundle.getString("msgData");
                        String type = bundle.getString("type");
                        LogUtils.e(tag, "==bundle===msgData======" + msgData);
                        LogUtils.e(tag, "==bundle===type======" + type);
                        if (BaseActivity.getForegroundActivity() == null)
                            return;
                        switch (type){
                            case PUSH_NOTICE:
                                MarqueeEntity bean = GsonUtils.getInstance().fromJson(msgData, MarqueeEntity.class);
                                if (bean.getRollTime() < 1){
                                    BaseActivity.getForegroundActivity().missRollMsg(true);
                                    return;
                                }
                                BaseActivity.getForegroundActivity().showRollMsg(bean);
                                break;
                            case PUSH_INSERT:
                                if (BaseActivity.getForegroundActivity() instanceof InsertActivity){//插入更新
                                    BaseActivity.getForegroundActivity().conTrollShow(Constant.PUSH_INSERT_MSG, msgData);
                                } else {
                                    BaseActivity.getForegroundActivity().insertRes(msgData);
                                }
                                break;
                        }
                        break;
                    case Constant.SET_SNAP_PIC:
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            String fileName = bundle.getString("args0");
                            LogUtils.e(tag, "==bundle===takeScreenShot===1===" + fileName);
                            BaseActivity.getForegroundActivity().takeScreenShot(fileName);
                            LogUtils.e(tag, "==bundle===takeScreenShot===2===" + state);
                        }
                        break;
                    case Constant.SET_SERVICE_IP://设置服务器ip，重新认证
                        String serviceIp = bundle.getString("args0");
                        if (BaseActivity.getForegroundActivity() != null)
                            BaseActivity.getForegroundActivity().connectSer(serviceIp);
                        return;
                    case Constant.SET_MEDIA_DATA://设置任务发布
                        String infoType = bundle.getString("args0");
                        String infoUrl = bundle.getString("args1");
                        LogUtils.e(tag, "===infoType===" + infoType);
                        LogUtils.e(tag, "===infoUrl===" + infoUrl);
                        LogUtils.e(tag, "===getForegroundActivity===" + BaseActivity.getForegroundActivity());
                        info.setMediaUrl(infoUrl);
                        info.setMediaType(infoType);
                        FileData.setDeviceInfo(info);
                        UShared.putString(Constant.PUBLISH_TYPE, infoType);
                        UShared.putString(Constant.PUBLISH_URL, infoUrl);
                        if (BaseActivity.getForegroundActivity() != null){
                            BaseActivity.getForegroundActivity().checkStart(infoType);
                            BaseActivity.getForegroundActivity().conTrollShow(state, infoType, infoUrl);
                        }
                        break;
                    case Constant.REFRESH_WEB://页面刷新，GC
                        if (BaseActivity.getForegroundActivity() instanceof WebActivity)
                            BaseActivity.getForegroundActivity().conTrollShow(state, "");
                        break;
                    case Constant.UPDATE_APPLICATION://应用apk更新
                        break;
                    case Constant.SET_VOICE_SPEED://设置语音播报速度
                        String voiceSpeed = bundle.getString("args0");
                        Log.e(tag, "-----voiceSpeed------" + voiceSpeed);
                        if (Utils.getStringValue(voiceSpeed).isEmpty())
                            return;
                        Constant.voiceSpeed = voiceSpeed;
                        return;
                    case Constant.SET_CACHE_SIZE://设置视频缓存大小
                        String cacheSize = bundle.getString("args0");
                        Log.e(tag, "-----cacheSize------" + cacheSize);
                        if (Utils.getStringValue(cacheSize).isEmpty())
                            return;
                        Constant.cacheSize = Integer.parseInt(cacheSize);
                        break;
                    case Constant.CLEAR_ALL_CACHE://清楚所有视频缓存
                        String filePath = FileUtils.getPath(Constant.CACHE_FOLDER);
                        Utils.deleteFolder(filePath);
                        if (BaseActivity.getForegroundActivity() instanceof ImageActivity)
                            BaseActivity.getForegroundActivity().conTrollShow(state, "");
                        break;
                }
                if (BaseActivity.getForegroundActivity() == null)
                    return;
                if (Constant.DIALOG_IS_SHOW)
                    checkConnect(context);
                break;
            case "android.net.conn.CONNECTIVITY_CHANGE":
                LogUtils.e(tag, "=====getForegroundActivity======" + BaseActivity.getForegroundActivity());
                if (BaseActivity.getForegroundActivity() == null)
                    return;
                checkConnect(context);
                if ( Constant.NET_STATE) {
                    NetInterface.checkTool();//检查更新工具是否有关闭
                } else {
                    UShared.putLong(Constant.DEVICE_OPEN_TIME, System.currentTimeMillis() / 1000);
                }
                LogUtils.e(tag, "=====NET_STATE======" + Constant.NET_STATE  );
                AEvent.notifyListener(AEvent.TO_TOAST, true, Constant.NET_STATE ? "网络已连上" : "网络连接断开!!");
//                BaseActivity.getForegroundActivity().handler.post(() -> Utils.showShortToast(Constant.NET_STATE ? "网络已连上" : "网络连接断开!!"));
                BaseActivity.getForegroundActivity().conTrollShow(Constant.INTERNET_CHANGE, "");
                break;
        }
    }

    private void checkConnect(Context context){
        Constant.NET_STATE = NetUtils.isNetworkAvailable(context);
        if (Constant.NET_STATE) {//设备有网，同时认证未成功时连接
            BaseActivity.getForegroundActivity().requestPermission();
        }
    }

    private DataEntity getInfo(){
        return FileData.getDeviceInfo(3);
    }

    private void startSelf(Context context, DataEntity info, String ... data){
        if (!Constant.APP_RESTART){
            return;
        }
        Class toClass = WebActivity.class;
//        if (info != null){
//            switch (info.getMediaType()){
//                case Constant.PUBLISH_SOURCE:
//                    toClass = ImageActivity.class;
//                    break;
//                case Constant.PUBLISH_LIVE:
//                    toClass = LiveActivity.class;
//                    break;
//                case Constant.PUBLISH_WEB:
//                default:
//                    toClass = WebActivity.class;
//                    break;
//            }
////            if (info.getHistoryNum() < 1) {
////                toClass = WebActivity.class;
////                Utils.showShortToast("请先设备认证");
////            }
//            ILog.e(tag, "==信发msg===toClass======" + toClass + "==getMediaType==" + info.getMediaType());
//        } else {
//            toClass = WebActivity.class;
//        }
        //启动当前主界面
        Intent i = new Intent(context, toClass);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (data.length > 0) {
            UShared.putString("ipStr_new", data[0]);
        }
        context.startActivity(i);
    }

    /**
     * 更新最近一次app在线时间
     */
    public static void sendBroad(Context context){
        if (doubleClick())
            return;
        String msgData = UShared.getString(Constant.PUBLISH_BASE);
        LogUtils.e("XINFA_alertHome", "=====sendBroad==ReceiverMsg==" + Constant.toAim + ",data=" + msgData);
        Intent intent = new Intent(Constant.RECEIVE_FORM_LELDIPS);
        Bundle bundle = new Bundle();
        bundle.putInt("startAim", Constant.toAim);
        bundle.putString("baseEntity", msgData);
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }

    private static long time_Double = 0;
    /*
     * 防止连续点击
     */
    public synchronized static boolean doubleClick() {//需求：toast在未消失的时候第二次点击有效（能正常推出）
        long time = System.currentTimeMillis();
        if (time - time_Double < 500) {
            return true;
        }
        time_Double = time;
        return false;
    }
}
